/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.mediaplayerdemo.widget;

import com.example.mediaplayerdemo.ResourceTable;
import ohos.agp.components.Component;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.TextField;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;

/**
 * InputDialog
 */
public class InputDialog extends CommonDialog {

    private final Context context;
    private Callback callback;

    /**
     * 构造函数
     * @param context context
     */
    public InputDialog(Context context) {
        super(context);

        this.context = context;

        setTransparent(true);
        setSize(MATCH_PARENT, MATCH_PARENT);

        Component component = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_layout_dialog, null, false);
        setContentCustomComponent(component);

        Component.ClickedListener hide = l -> hide();

        Component parent = component.findComponentById(ResourceTable.Id_parent);
        parent.setClickedListener(hide);

        Component content = component.findComponentById(ResourceTable.Id_content);
        content.setWidth(getWidth());
        content.setClickedListener(l -> {});

        Component cancel = component.findComponentById(ResourceTable.Id_cancel);
        cancel.setClickedListener(hide);

        TextField field = (TextField) component.findComponentById(ResourceTable.Id_text);

        Component ok = component.findComponentById(ResourceTable.Id_ok);
        ok.setClickedListener(l -> {
            if (callback != null) callback.onSure(field.getText());
            hide();
        });
    }

    /**
     * setCallback
     * @param callback callback
     */
    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    private int getWidth() {
        return context.getResourceManager().getDeviceCapability().width *
                context.getResourceManager().getDeviceCapability().screenDensity / 160 - 150;
    }

    /**
     * Callback
     */
    public interface Callback {
        /**
         * onSure
         * @param text text
         */
        void onSure(String text);
    }
}
